package com.gege;

import java.util.concurrent.*;

/**
 * 使用 CountDownLatch
 * <p>
 * CountDownLatch 是基于同步器(AQS)的
 * <p>
 * CountDownLatch 同步状态的获取与释放是"共享式"的
 * 当 tryAcquireShared 返回值大于等于0时,表示能够获取到同步状态
 * <p>
 * tryReleaseShared(int arg) 方法必须确保同步状态(或者资源数)线程安全释放,一般是通过循环和CAS来保证的,
 * 因为释放同步状态的操作会同时来自多个线程。
 *
 * @author gechenpeng
 * @date 2021-04-13
 */
public class Demo5 {

    public static void main(String[] args) throws Exception {
        final CountDownLatch countDownLatch = new CountDownLatch(1);

        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1024),
                new ThreadPoolExecutor.CallerRunsPolicy());

        long start = System.currentTimeMillis();

        Future<String> future = executorService.submit(() -> {
            try {
                return execute();
            } finally {
                countDownLatch.countDown();
            }
        });

        executorService.shutdown();

        countDownLatch.await();

        String message = future.get();

        System.out.println("线程运行的结果是: " + message + ", 耗时: " +
                (System.currentTimeMillis() - start) + " ms");
    }

    private static String execute() throws Exception {
        Thread.sleep(5000);
        return "ok";
    }
}
